package t3dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import t3jdbc.JDBCUtil;

public class Dao {

	protected Connection conn = null;
	protected PreparedStatement ps = null;
	protected ResultSet rs = null;

	public int dml(String sql, List<Object> list) throws SQLException {
		int back;
		try {
			conn = JDBCUtil.getConnection();
			conn.setAutoCommit(false);
			ps = conn.prepareStatement(sql);
			for (int i = 0; i < list.size(); ++i) {
				ps.setObject(i + 1, list.get(i));
			}
			back = ps.executeUpdate();
			conn.commit();
			return back;
		} catch (ClassNotFoundException | SQLException e) {
			e.printStackTrace();
			conn.rollback();
		} finally {
			JDBCUtil.close(conn, ps);
			conn = null;
			ps = null;
		}
		return 0;
	}

	public ResultSet dql(String sql, List<Object> list) throws SQLException {
		try {
			conn = JDBCUtil.getConnection();
			conn.setAutoCommit(false);
			ps = conn.prepareStatement(sql);
			for (int i = 0; i < list.size(); ++i) {
				ps.setObject(i + 1, list.get(i));
			}
//			System.out.println(sql);
			rs = ps.executeQuery();
			conn.commit();
			return rs;
		} catch (ClassNotFoundException | SQLException e) {
			e.printStackTrace();
			conn.rollback();
		} finally {
//			JDBCUtil.close(conn, ps);
//			conn=null;
//			ps=null;
		}
		return null;
	}
}
